package com.seven.monior;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ServiceInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

import com.seven.monior.AppInfo.AppInfo;
import com.seven.monior.AppInfo.AppItemAdapter;
import com.seven.monior.AppInfo.Global;

public class Apps extends ListActivity {
	private ActivityManager am;
	private List<RunningTaskInfo> mRunningTaskInfos;
	private List<RunningAppProcessInfo> mRunningAppProcessInfos;
	private PackageManager pm;
	private ArrayList<AppInfo> mList;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
		mRunningTaskInfos = am.getRunningTasks(30);
		mRunningAppProcessInfos = am.getRunningAppProcesses();

		pm = this.getPackageManager();
		mList = getData(pm);

		// AppItemAdapter adapter = new
		// AppItemAdapter(this,mList,R.layout.apps_list_item,new
		// String[]{"appName","appSize","appVersion"},new
		// int[]{R.id.appName,R.id.appSize,R.id.appVersion}, new
		// Drawable[]{},R.id.appIcon);
		// SimpleAdapter adapter = new
		// SimpleAdapter(this,mList,R.layout.apps_list_item,new
		// String[]{"appIcon","appName","appSize","appVersion"},new
		// int[]{R.id.appIcon,R.id.appName,R.id.appSize,R.id.appVersion});
		// setListAdapter(adapter);

		AppItemAdapter adapter = new AppItemAdapter(this);

		// Resources res = this.getResources();
		adapter.AddData(mList);

		setListAdapter(adapter);

		// for(int i=0;i<mList.size();i++){
		// Map<String, Object> item=mList.get(i);
		//
		// Long ll=adapter.getItemId(i);
		//
		// ImageView iv
		// =(ImageView)this.getChildAt(i).findViewById(R.id.appIcon);
		// iv.setImageDrawable(appicon);
		// }

		// try {
		//
		// PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
		// String packageName = info.packageName;
		// int versionCode = info.versionCode;
		// String versionName = info.versionName;
		//
		// TextView textview = new TextView(this);
		// textview.setText(packageName);
		// setContentView(textview);
		//
		//
		// } catch (NameNotFoundException e) {
		// // TODO Auto-generated catch block
		// }

	}

	private ArrayList<AppInfo> getData(PackageManager pm) {
		ArrayList<AppInfo> data = new ArrayList<AppInfo>();
		List<PackageInfo> packageInfos = pm
				.getInstalledPackages(PackageManager.GET_PERMISSIONS);

		for (int i = 0; i < packageInfos.size(); i++) {
			PackageInfo pInfo = packageInfos.get(i);
			Drawable dAppIcon = pInfo.applicationInfo.loadIcon(pm);
			String strPackageName = pInfo.packageName;
			String strAppName = pInfo.applicationInfo.loadLabel(pm).toString();
			String strAppSize = String.valueOf(i * i);
			String strAppVersion = pInfo.versionName;
			ArrayList<String> strarrAppPermission = new ArrayList<String>();
			ArrayList<RunningAppProcessInfo> processes = new ArrayList<RunningAppProcessInfo>();

			Boolean bIsRunning = false;
			// Log.e("App packageName", pInfo.applicationInfo.processName);

			/*
			 * for(RunningTaskInfo runningTaskInfo : mRunningTaskInfos){ String
			 * taskName=runningTaskInfo.baseActivity.getClassName();
			 * if(taskName==pInfo.applicationInfo.processName){ bIsRunning=true;
			 * Log.e("App processName", pInfo.applicationInfo.packageName);
			 * Log.d("Task Name", taskName); } Log.d("Task Name", taskName); }
			 * 
			 * Log.d("App Name", strAppName);
			 */

			/*
			 * FeatureInfo[] featureInfos=pInfo.reqFeatures;
			 * if(featureInfos!=null){ for(int t=0;t<featureInfos.length;t++){
			 * FeatureInfo fInfo=featureInfos[t]; Log.w("FeatureInfo",
			 * fInfo.name); } }
			 */

			/*
			 * PermissionInfo[] permissionInfos=pInfo.permissions;
			 * 
			 * if(permissionInfos!=null){ //Log.d("length",
			 * String.valueOf(permissionInfos.length)); for(int
			 * t=0;t<permissionInfos.length;t++){ String info = "";
			 * 
			 * try{ CharSequence cs=permissionInfos[t].loadDescription(pm);
			 * if(cs!=null&&cs.length()>0){ info=cs.toString();
			 * strarrAppPermission.add(info); Log.w("PermissionInfo",
			 * permissionInfos[t].protectionLevel+"  "+permissionInfos[t].name);
			 * }
			 * 
			 * 
			 * 
			 * if(permissionInfos[t].group!=null){ Log.d("NAME",
			 * permissionInfos[t].group); PermissionGroupInfo
			 * pgi=pm.getPermissionGroupInfo(permissionInfos[t].group,
			 * PackageManager.GET_PERMISSIONS); CharSequence
			 * css=pgi.loadDescription(pm); if(cs!=null&&cs.length()>0){
			 * //Log.w("PermissionGroup", css.toString()); } }
			 * 
			 * } catch (Exception e) { // TODO: handle exception Log.e("ERROR",
			 * e.toString()); } }
			 * 
			 * } else{ Log.e("PermissionInfo", "PERMISSION IS NULL"); }
			 */

			String[] piPermissions = pInfo.requestedPermissions;
			if (piPermissions != null) {
				String strPermission = "";
				for (int k = 0; k < piPermissions.length; k++) {
					strPermission = piPermissions[k];
					if (pm.checkPermission(strPermission, pInfo.packageName) == PackageManager.PERMISSION_GRANTED) {
						try {
							String strPermissionGroup = pm
									.getPermissionInfo(strPermission,
											PackageManager.GET_META_DATA).group;
							// Log.w("RequestPermissionInfoGROUP",
							// strPermissionGroup);
							// Log.w("RequestPermissionInfo", strPermission);
						} catch (Exception e) {
							// TODO: handle exception
							// Log.e("ERROR", "Get Permission Group failed!");
						}
					} else if (pm.checkPermission(strPermission,
							pInfo.packageName) == PackageManager.PERMISSION_DENIED) {
						// Log.e("RequestPermissionInfo", strPermission);
					}
				}

			} else {
				// Log.e("RequestPermissionInfo", "PERMISSION IS NULL");
			}

			// Log.d("END OF App Name", strAppName);

			AppInfo item = new AppInfo(strPackageName, strAppName, strAppName,
					strAppVersion, 1, dAppIcon, strarrAppPermission,
					bIsRunning, processes);

			data.add(item);
		}
		// sort data by a-z
		Comparator<AppInfo> sortByName = new Comparator<AppInfo>() {

			@Override
			public int compare(AppInfo ai1, AppInfo ai2) {
				// TODO Auto-generated method stub
				String name1 = ai1.getAppName().toLowerCase();
				String name2 = ai2.getAppName().toLowerCase();

				return name1.compareTo(name2);
			}
		};

		Collections.sort(data, sortByName);

		// add running process info

		for (RunningAppProcessInfo runningAppProcessInfo : mRunningAppProcessInfos) {
			String processName = runningAppProcessInfo.processName;

			for (String pkgName : runningAppProcessInfo.pkgList) {
				for (int t = 0; t < data.size(); t++) {
					AppInfo appInfo = data.get(t);
					if (appInfo.getPackageName().equalsIgnoreCase(pkgName)) {
						// ProcessOfPackage processPkg=new
						// ProcessOfPackage(processName, true);
						appInfo.addProcessInfo(runningAppProcessInfo);
						// Log.e("AppInfo.getAppName", appInfo.getAppName());
						// Log.d("AppInfo.getPackageName",appInfo.getPackageName());
						// Log.e("runningAppProcessInfo.pkg", pkgName);
						// Log.d("runningAppProcessInfo.processName",
						// runningAppProcessInfo.processName);
					}
				}
			}

			// Log.d("process Name", processName);
		}

		return data;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		AppInfo appInfo = new AppInfo();
		Global.appInfo = mList.get(position);
		Intent intent = new Intent().setClass(this, AppDetail.class);
		Bundle bundle = new Bundle();

		// Log.e("CallLogActivity",appInfo.AppInfoDetail());

		// startActivity(intent);

		/*
		 * LinearLayout linearLayout_processes = (LinearLayout) v
		 * .findViewById(R.id.linearLayout_processes); if
		 * (linearLayout_processes.getVisibility() == View.VISIBLE)
		 * linearLayout_processes.setVisibility(View.GONE); else
		 * linearLayout_processes.setVisibility(View.VISIBLE);
		 */

		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setClassName("com.android.settings",
				"com.android.settings.InstalledAppDetails");
		i.putExtra("com.android.settings.ApplicationPkgName",
				Global.appInfo.getPackageName());
		startActivity(i);

		super.onListItemClick(l, v, position, id);
	}

	private ArrayList<String> getProcessNames(PackageInfo pInfo) {
		ArrayList<String> processNames = new ArrayList<String>();
		ActivityInfo[] arrayActivityInfos = pInfo.activities;
		ProviderInfo[] arrayProviderInfos = pInfo.providers;
		ActivityInfo[] arrayReceiverInfos = pInfo.receivers;
		ServiceInfo[] arrayServiceInfos = pInfo.services;

		for (ActivityInfo activityInfo : arrayActivityInfos) {
			Boolean bExist = false;
			for (String arrayItem : processNames) {
				if (arrayItem.equalsIgnoreCase(activityInfo.processName))
					bExist = true;
			}
		}

		return processNames;
	}

	/*
	 * private List<Map<String, Object>> _getData(PackageManager pm) {
	 * List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	 * 
	 * List<PackageInfo> packageInfos= pm.getInstalledPackages(0); for(int
	 * i=0;i<packageInfos.size();i++){ PackageInfo pInfo=packageInfos.get(i);
	 * 
	 * 
	 * Drawable dAppIcon=pInfo.applicationInfo.loadIcon(pm);
	 * 
	 * String strAppName=pInfo.applicationInfo.loadLabel(pm).toString(); String
	 * strAppSize=String.valueOf(i*i); String strAppVersion=pInfo.versionName;
	 * Map<String, Object> map = new HashMap<String, Object>();
	 * map.put("appIcon", dAppIcon); map.put("appName", strAppName);
	 * map.put("appSize", strAppSize); map.put("appVersion", strAppVersion);
	 * list.add(map); }
	 * 
	 * 
	 * return list;
	 * 
	 * }
	 */
}
